package com.ruoyi.demo.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import jodd.util.ThreadUtil;
import jodd.util.Util;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * <简述>
 * <详细描述>
 *
 * @author syf
 * @date 2024年05月18日 13:19
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class ThreadPoolTest {
    private final ThreadPoolTaskExecutor threadPoolTaskExecutor;

//    @Autowired
//    @Qualifier("threadPoolTaskExecutor")
//    private  ThreadPoolTaskExecutor ThreadPoolTaskExecutor;

    @SaIgnore
    @GetMapping("testPool1")
    public String testPool1() {
        log.info("--------------------------->主线程");
        Future<?> submit = threadPoolTaskExecutor.submit(new Runnable() {
            @Override
            public void run() {
                method();
            }
        });
        return "ok";
    }

    /**
     * <简述>
     * <详细描述>
     * @author syf
     * @date 2024/5/18 13:27
     */
    public void method() {
        log.info("--------------------------->子线程：method");
        ThreadUtil.sleep(3000);
    }


    //--------------------------------对比
    /**
     * <简述>打印十个数字同步 10秒
     * <详细描述>
     * @author syf
     * @date 2024/5/18 14:17
     */
    @SaIgnore
    @GetMapping("testPool2")
    public String testPool2() {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < 10 ;i++){
                ThreadUtil.sleep(1000);
            list.add(i);
        }
        log.info("testPool2--->:{}",list);
        return "ok";
    }

/**
 * <简述>打印十个数字异步 1秒
 * <详细描述>
 * @author syf
 * @date 2024/5/18 14:17
 */
@SaIgnore
    @GetMapping("testPool3")
    public void testPool3() {
        ArrayList<Future<Integer>> futures = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            int temp = i;
            Future<Integer> submit = threadPoolTaskExecutor.submit(() -> {
                ThreadUtil.sleep(1000);
                return temp;
            });
            futures.add(submit);
        }

        ArrayList<Integer> list = new ArrayList<>();
        for (Future<Integer> en : futures) {
            try {
                Integer integer = en.get();
                list.add(integer);
            } catch (ExecutionException | InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        log.info("testPool3--->:{}", list);
    }

}
